﻿using KingerRobot.MexicoSailunMDC.Spi;
using KingerRobot.MexicoSailunMDC.SpiService;
using System.Diagnostics;
using System.Threading.Tasks;
using Z.EntityFramework.Extensions;

namespace KingerRobot.MexicoSailunMDC.Biz;
/// <summary>
/// 入库扫描仪任务执行 找任务下发
/// </summary>
public class LineScannerExecuteBiz : K8.MDCBB.Biz
{
    private const string ClassName = nameof(LineScannerExecuteBiz);


    #region 配置参数
    private ParamData Param { get; set; }

    class ParamData
    {

        /// <summary>
        /// 下传位所属的开始扫描仪位置(以此为准)
        /// </summary>
        public long StartScannerLoc { set; get; }
    }
    #endregion

    #region PLC 通讯参数
    private ValueData Data { get; set; }
    class ValueData
    {
        ///// <summary>
        ///// 产品条码
        ///// </summary>
        //public string ProductCode { get; set; }

        /// <summary>
        /// 计数
        /// </summary>
        //public long TireCount { get; set; }
        /// <summary>
        /// 读取任务号（上段线体任务读取后【有值】）才下传新任务
        /// </summary>
        public int RWorkNo { get; set; }
        /// <summary>
        /// 0:PLC读取后可改成 0
        /// 1:WCS任务下传完成..............可读可写/WCS读取到 0，下发任务，PLC接收到 1，改为 0。
        /// </summary>
        //public int TaskFlag { get; set; }

        /// <summary>
        /// 功能状态 (读取高度类型)
        /// </summary>
        //public int RStatus { get; set; } = -1;
    }
    #endregion

    #region 缓存
    private CacheData Cache { get; set; }
    class CacheData
    {
        /// <summary>
        /// 计数
        /// </summary>
        public long TireCount { get; set; }

        /// <summary>
        /// 条码
        /// </summary>
        public string ProductCode { get; set; }

        /// <summary>
        /// 此条码用做判断在下传位置是否插入到中间表
        /// </summary>
        public string ScannerProductCode { get; set; }

    }
    #endregion

    #region 实时日志
    private StepData Step { get; set; }
    class StepData
    {
        private string _msg = string.Empty;
        public string StepMsg
        {
            get
            {
                return this._msg;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this._msg = string.Empty;
                    return;
                }
                this._msg = $"{ClassName}|{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}>>{value}";
            }
        }
        public int RStatus { get; set; }
    }
    private void StepMsg(string msg)
    {
        this.Step.StepMsg = msg;
        WriteLog(msg);
    }
    #endregion

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message)
    {
        K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
    }
    #endregion 

    /// <summary>
    /// 和 PLC 通讯对象
    /// </summary>
    private BizData BizData { get; set; }


    public int Execute(BizData writer)
    {
        this.StepMsg($"开始下穿");//10:40:17.054
        var result = 0;
        try
        {
            // Excute 方法外使用 BizData
            this.BizData = writer;

            //this.StepMsg($"条码开始执行下发");
            int heightType = 0;// Data.RStatus;

            long startLoc = Param.StartScannerLoc;
            // 返回参数
            result = 0;
            //if (Data.TaskFlag == (int)EnumLineAck.WCSDownFinish)
            //{
            //    // 已扫描条码
            //    this.StepMsg($" {Data.WorkNo}任务下传完成，但PLC未读取成功:{Data.TaskFlag}【PLC读取后可改成 0】");
            //    return result;
            //}

            //this.StepMsg($"条码开始创建rpc");
            ////var taskService = K8.RSF.Client.Create<ITaskService>();
            this.StepMsg($"条码创建rpc完成");
            BizTaskBeanV2 task = new();
            ITaskService taskService = K8.RSF.Client.Create<ITaskService>();
            //try
            //{
            //    taskService = new TaskImpl();
            //    task = taskService.GetTaskByExecuteStartLoc(startLoc);
            //    this.StepMsg($"走直接创建方法");
            //}
            //catch (Exception ex)
            //{

            task = taskService.GetTaskByExecuteStartLoc(startLoc);
            this.StepMsg($"异222,走Rpc方法");
            //}
            if (task is null)
            {
                this.StepMsg($"不存在未执行的入库任务");
                return result;
            }
            var mark = SetTaskInfo(task);
            if (mark > 0)
            {
                if (mark > 0)
                {
                    // 执行、保存缓存
                    //修改任务下发状态
                    taskService.UpdateTaskDown(task.TaskNo, 1);
                    this.StepMsg($"条码：{task.ProductCode},任务{task.TaskNo}- 修改状态");
                    //任务先不执行
                    var service = K8.RSF.Client.Create<IWarehousingBeforeService>();
                    service.ExecuteTask(task.TaskNo ?? 0, startLoc);
                    this.StepMsg($"条码：{task.ProductCode},任务{task.TaskNo}-执行完成");
                    //Cache.ProductCode = task.ProductCode;
                }
            }
            //this.StepMsg($"条码：{task.ProductCode},下传完成300");//10:40:17.054
            //}
        }
        catch (Exception ex)
        {
            this.StepMsg($"下穿异常{ex.ToString()}");//10:40:17.054
        }
        return result;
    }


    private int SetTaskInfo(BizTaskBeanV2 task)
    {
        var result = 0;
        var sProductCode = task.ProductCode;

        //如果是出库任务 则为直运类型 目的地plccode取指令的plccode
        string destination = task.TargetPlcLoc;
        if (task.TaskType == (int)EnumTaskType.Exwarehouse)
        {
            destination = task.TargetCmdPlcLoc;
        }

        var taskNo = task.TaskNo;
        var outSize = task.OutSize;
        var groupNo = task.TaskGroup;
        this.StepMsg($"获取任务完成,task{task.ToJson()}");
        //if (string.IsNullOrWhiteSpace(destination) || string.IsNullOrWhiteSpace(sProductCode) || destination == "0" || taskNo == 0)
        //{
        //    this.StepMsg($"下传失败,参数异常{task.ToJson()}");
        //    return 0;
        //}


        try
        {
            this.StepMsg($"任务{taskNo}开始下传11111");

            if (destination.Contains("9999") || destination.Contains("8888"))
            {
                result = this.BizData.WriteData(new
                {
                    Destination = destination,        // 目标地址： 如果是异常胎下达目的地是9999,正常胎下达目的地是8888
                    WorkNo = taskNo,                   // 流水号
                    GroupId = destination,                 // 组号
                });
            }
            else
            {
                result = this.BizData.WriteData(new
                {
                    Destination = destination,        // 目标地址： 如果是异常胎下达目的地是9999,正常胎下达目的地是8888
                    WorkNo = taskNo,                   // 流水号
                    GroupId = groupNo,                 // 组号
                });
            }
            this.StepMsg($"任务{taskNo}下传完成,,{result}");

        }
        catch (Exception ex)
        {
            this.StepMsg($"任务{taskNo}下传失败1,参数异常{task.ToJson()}");
            return 0;

        }
        return 1;
    }
    /// <summary>
    /// 获取拆分条码
    /// </summary>
    /// <param name="codes"></param>
    /// <param name="ind">从1开始</param>
    /// <returns></returns>
    private string GetProductItem(List<char[]> codes, int ind)
    {
        if (codes.Count >= ind)
        {
            return new string(codes[ind - 1]);
        }
        return string.Empty;
    }
    private int SetTaskFlag()
    {
        var mark = this.BizData.WriteData(new
        {
            TaskFlag = EnumLineAck.WCSDownFinish,
        });
        Thread.Sleep(100);
        return mark;
    }
}
